package com.example.androidadvance01;

import androidx.appcompat.app.AppCompatActivity;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;

public class MainActivity extends AppCompatActivity {

    private EditText word;
    private EditText transition;
    private Button write;
    private Button read;

    private TextView show;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //绑定控件
        word = findViewById(R.id.word);
        transition = findViewById(R.id.transition);
        show = findViewById(R.id.show);
        write = findViewById(R.id.write);
        read = findViewById(R.id.read);


        //获取 sharepreferences 控件
        SharedPreferences preferences = getSharedPreferences("words",MODE_PRIVATE);

        write.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //添加单词
                SharedPreferences.Editor edit = preferences.edit();
                edit.putString("word",String.valueOf(word.getText()));
                edit.putString("tran",String.valueOf(transition.getText()));
                Boolean isTrue = edit.commit();
                if (isTrue){
                    word.setText("");
                    transition.setText("");
                }
            }
        });

        read.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                show.setText( preferences.getString("word","")+" "
                        + preferences.getString("tran","您的备忘录为空"));
            }

        });





        //在file目录中保存文本文件
        try {
            saveTextOnFile();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    private void saveTextOnFile() throws IOException {
        //1.获取files目录
        String fileDir = getFilesDir().getAbsolutePath();
        //2.创建输入流
        BufferedWriter writer = new BufferedWriter(
                new OutputStreamWriter(
                new FileOutputStream(fileDir+"/text.txt")) );
        //3.向流内写数据
        writer.write("adafafdfdada");
        writer.newLine();
        writer.flush();
        //4.关闭流
        writer.close();

    }
}